/**
 * this is intended to be a drop in replacement for
 * the rpc.JsonService, for testing
 * 
 * while jsonService calls a url with a form post of the json params/method
 * this loads a page that is expected to be a json object. (or an array of json objects,
 * in which only the first is used)
 * the object must have methods defined that match the SMD for the
 * service. each method should return an object with id/result/error
 * as per the rpc protocol.
 * 
 * this is a great way to develop without worrying about
 * the server. then you hand the server people your
 * SMD which is the "design contract" between the
 * UI layer and the server, and you are done. they
 * can build their side in any language that adheres to
 * the smd.
 * 
 * 
 * @author maulin
 */
dojo.provide("medryx.rpc.MockJsonService");
dojo.require("dojo.rpc.JsonService");

dojo.declare("medryx.rpc.MockJsonService", [dojo.rpc.JsonService], {
	
	/**
	 * this overwrites the bind in the original service.
	 * it loads the page in the service url first.
	 * the page should have be javascript object
	 * that has the method that accepts the given
	 * params and returns the result object
	 * @param {Object} method
	 * @param {Object} parameters
	 * @param {Object} deferredRequestHandler
	 * @param {Object} url
	 */
	bind: function(method, parameters, deferredRequestHandler, url){
            var def = dojo.xhrPost({
                url: url||this.serviceUrl,
                timeout: this.timeout, 
                handleAs: "json-comment-optional"
            });
            def.addCallbacks(this.resultCallback(deferredRequestHandler, method, parameters), this.errorCallback(deferredRequestHandler));
    },
	
	/**
	 * this will apply the method and params of the request
	 * to the received object, and then pass the results
	 * to the callback of the deferredRequestHandler
	 * 
	 * @param {Object} deferredRequestHandler
	 */
	resultCallback:function(deferredRequestHandler, method, parameters) {
		
		  var tf = dojo.hitch(this, 
            function(mock){
				var obj;
				if (dojo.isArray(mock)) {
					mock = mock[0];
				}
				if (!mock[method]) {
				    obj = {id:'unknown', error:{code:-1, message:"Method not implemented."}};
				} else {
					obj = mock[method](parameters);
				}
                if(obj.error!=null){
                    var err;
                    if(typeof obj.error == 'object'){
                        err = new Error(obj.error.message);
                        err.code = obj.error.code;
                        err.error = obj.error.error;
                    }else{
                        err = new Error(obj.error);
                    }
                    err.id = obj.id;
                    err.errorObject = obj;
                    deferredRequestHandler.errback(err);
                }else{
                    deferredRequestHandler.callback(this.parseResults(obj)); 
                }
            }
        );
        return tf;
	}
		
});
